package com.my.kindlesend.service.impl;

import com.my.kindlesend.dao.UploadFileDao;
import com.my.kindlesend.dao.UserInfoDao;
import com.my.kindlesend.enums.FileSendStatusEnum;
import com.my.kindlesend.entity.UploadFile;
import com.my.kindlesend.entity.UserInfo;
import com.my.kindlesend.service.UploadFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 上传文件服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UploadFileServiceImpl implements UploadFileService {

    private final UploadFileDao uploadFileDao;
    private final UserInfoDao userInfoDao;

    /**
     * 保存上传文件信息
     * 设置文件上传时间并持久化到数据库
     * @param uploadFile 上传文件信息对象
     * @return 保存后的上传文件信息对象
     */
    @Override
    @Transactional
    public UploadFile saveUploadFile(UploadFile uploadFile) {
        // 设置文件上传时间
        uploadFile.setCreateTime(LocalDateTime.now());
        // 保存上传文件信息到数据库
        return uploadFileDao.save(uploadFile);
    }
    
    /**
     * 根据openId查询用户的上传文件列表
     * @param openId 用户的openId
     * @return 用户的上传文件列表
     */
    @Override
    public List<UploadFile> getUploadFilesByOpenId(String openId) {
        log.info("根据openId查询上传文件列表: {}", openId);
        
        // 根据openId查询用户信息
        Optional<UserInfo> userInfoOptional = userInfoDao.findByOpenId(openId);
        if (userInfoOptional.isEmpty()) {
            log.warn("未找到用户信息，openId: {}", openId);
            return Collections.emptyList();
        }
        
        // 使用用户ID查询上传文件列表，并按创建时间倒序排序
        UserInfo userInfo = userInfoOptional.get();
        List<UploadFile> uploadFiles = uploadFileDao.findByUserInfoIdOrderByUpdateTimeDesc(userInfo.getId());
        log.info("查询到用户[{}]的上传文件数量: {}", userInfo.getId(), uploadFiles.size());
        
        return uploadFiles;
    }
    
    /**
     * 将文件发送状态重置为未发送
     * @param fileId 文件ID
     * @param openId 用户的openId
     * @return 是否重置成功
     */
    @Override
    @Transactional
    public boolean resetFileStatusToNotSent(Long fileId, String openId) {
        log.info("重置文件发送状态为未发送，fileId: {}, openId: {}", fileId, openId);
        
        // 根据openId查询用户信息
        Optional<UserInfo> userInfoOptional = userInfoDao.findByOpenId(openId);
        if (userInfoOptional.isEmpty()) {
            log.warn("未找到用户信息，openId: {}", openId);
            return false;
        }
        
        // 根据fileId查询文件信息
        Optional<UploadFile> uploadFileOptional = uploadFileDao.findById(fileId);
        if (uploadFileOptional.isEmpty()) {
            log.warn("未找到文件信息，fileId: {}", fileId);
            return false;
        }
        
        // 验证文件是否属于该用户
        UploadFile uploadFile = uploadFileOptional.get();
        UserInfo userInfo = userInfoOptional.get();
        if (!uploadFile.getUserInfoId().equals(userInfo.getId())) {
            log.warn("文件不属于该用户，fileId: {}, userId: {}, expectedUserId: {}", 
                     fileId, uploadFile.getUserInfoId(), userInfo.getId());
            return false;
        }
        
        // 将文件状态更新为未发送
        uploadFile.setStatus(FileSendStatusEnum.NOT_SENT.getCode());
        uploadFile.setUpdateTime(LocalDateTime.now());
        
        // 保存更新后的文件信息
        uploadFileDao.save(uploadFile);
        log.info("文件状态已成功重置为未发送，fileId: {}", fileId);
        
        return true;
    }
}